#!/usr/bin/env python
import sys
import os
from metlib.shell import script_helper as sh

try:
    root_path = os.environ['G3S']
    print "#################################################"
    print "GlassSea Root path: %s" % (root_path,)
except NameError:
    print "Env G3S not set!"
    sys.exit(2)


def usage(pname=sys.argv[0]):
    print "Usage: %s CASENAME RUNTIME [RUNTAG]" % (pname,)
    sys.exit(1)

if len(sys.argv) < 3:
    usage()

casename = sys.argv[1]
runtime = sys.argv[2]

if len(sys.argv) >= 4:
    runtag = sys.argv[3]
    runname = '.'.join((casename, runtime, runtag))
    os.environ['RUNTAG'] = runtag
else:
    runtag = None
    runname = '.'.join((casename, runtime))
    os.environ['RUNTAG'] = ''
os.environ['CASENAME'] = casename
os.environ['RUNTIME'] = runtime
os.environ['RUNNAME'] = runname
print "Run info: %s" % (runname,)

# # create Runpool
print "Creating Runpool..."
try:
    rundir = root_path + '/runpool/' + runname
    os.makedirs(rundir)
except OSError, e:
    # TODO: already there?  cannot mkdir?
    if e.errno == 17:
        print "%s exists, not creating" % rundir
    else:
        print 'OSError! :' ,
        print e

# # setup
print "Setting up..."
sh.watchrun(cmd='%s/sys/util/SETUP' % root_path, 
    err_message='setting up case', \
    path='%s/case/%s' % (root_path, casename))

# # run 
#print "Running..."
#sh.watchrun(cmd='./G3S_start', 
#    err_message='running', path=rundir)

